package org.jeecg.common.util;

import com.itextpdf.text.pdf.PdfReader;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;

import java.lang.reflect.Field;

/**
 * @author thankgod7
 * @version 1.0
 * @date 2023/7/28 16:26
 */
public class ReadPageNumUtils {

    private static final String WORD_SUFFIX_DOC = ".doc";
    private static final String WORD_SUFFIX_DOCX = ".docx";

    private static final String PDF_SUFFIX = ".pdf";

    public static Integer read(String path) {
        if (path.toLowerCase().endsWith(PDF_SUFFIX)) {
            return readByPdf(path);
        } else if (path.toLowerCase().endsWith(WORD_SUFFIX_DOCX) || path.toLowerCase().endsWith(WORD_SUFFIX_DOC)) {
            return readByWord(path);
        } else {
            return 0;
        }
    }

    public static Integer readByPdf(String path) {
        try {
            // 读取源PDF文件
            PdfReader reader = new PdfReader(path);
            Field f = PdfReader.class.getDeclaredField("ownerPasswordUsed");
            f.setAccessible(true);
            f.set(reader, Boolean.TRUE);
            return reader.getNumberOfPages();
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    public static Integer readByWord(String path) {
        ActiveXComponent app = null;
        Dispatch doc;
        try {
            ComThread.InitSTA();
            app = new ActiveXComponent("Word.Application");
            //设置word不可见，否则会弹出word界面
            app.setProperty("Visible", false);
            //获得word中所有打开的文档,返回Documents对象
            Dispatch docs = app.getProperty("Documents").toDispatch();
            //调用Documents对象中Open方法打开文档，并返回打开的文档对象Document
            doc = Dispatch.call(docs, "Open", path, false, true).toDispatch();
            Dispatch selection = Dispatch.get(app, "Selection").toDispatch();
            int pages = Integer.parseInt(Dispatch.call(selection, "information", 4).toString());
            System.out.println(pages);
            //关闭文档
            Dispatch.call(doc, "Close", false);
            return pages;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        } finally {
            if (app != null) {
                //关闭word应用程序
                app.invoke("Quit");
            }
            ComThread.Release();
        }
    }

}
